package com.example.socketdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.socketdemo.util.CommonUtil;
import com.example.socketdemo.util.VibratorUtil;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity  {

    public static final String CONNECT = "10.10.100.254";

    public static final int REQUEST_CODE_SCAN = 0;

    private Myhandler myhandler = new Myhandler(this);

    private SocketConnectorThread connectorThread;

    private SendNumberThread sendNumberThread;

    private SZdialogadpter sZdialogadpter;

    private TextView tvResult;

    private Manager manager = Manager.getManager();

    Button connect;
    Button photo;
    TextView text;
    EditText etCode;


//    @Override
//    public void onClick(View v) {
//        switch (v.getId()){
//            case R.id.connect:
//
//                sZdialogadpter = new SZdialogadpter(MainActivity.this);
//                sZdialogadpter.setConnectLister(new SZdialogadpter.ConnectLister() {
//                    @Override
//                    public void connect(String IP, int Post) {
//                        socketinit("10.0.2.2", 9999);
//                        sZdialogadpter.dismiss();
//                    }
//                });
//                sZdialogadpter.show();
//
//                break;
//        }
//    }

    class Myhandler extends Handler {

        private WeakReference<MainActivity> weekActivity;
        private byte[] bytes;

        public Myhandler(MainActivity mainActivity) {
            this.weekActivity = new WeakReference<>(mainActivity);
        }


        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case -1://socket连接异常,抛出异常
                    Log.d("TAGGGGG", "handleMessage: " + "连接异常");
                    tvResult.setText("连接异常");
                    Toast.makeText(MainActivity.this, "连接异常", Toast.LENGTH_SHORT).show();
                    break;
                case 0:  //socket连接失败
                    Log.d("TAGGGGG", "handleMessage: " + "连接失败");
                    tvResult.setText("连接失败");
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:  //socket连接成功
                    Log.d("TAGGGGG", "handleMessage: " + "连接成功");
                    tvResult.setText("连接成功");
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    //数据处理 自己业务逻辑
                    Log.d("TAGGGGG", "handleMessage: " + "发送失败");
                    tvResult.setText("发送失败");
                    Toast.makeText(MainActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                    break;
                case 3: //接收消息断开标志
                    Log.d("TAGGGGG", "handleMessage: " + "发送消息异常");
                    tvResult.setText("发送数据异常,请尝试重新连接");
                    etCode.requestFocus();
                    Toast.makeText(MainActivity.this, "发送消息异常", Toast.LENGTH_SHORT).show();
                    break;
                case 5: //发送消息断开标志
                    Log.d("TAGGGGG", "handleMessage: " + "发送消息断开");
                    tvResult.setText("发送消息断开");
                    Toast.makeText(MainActivity.this, "发送消息断开", Toast.LENGTH_SHORT).show();
                    break;
                case 6: //发送成功
                    Log.d("TAGGGGG", "handleMessage: " + "发送成功");
                    tvResult.setText(msg.obj+"发送成功");
                    Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            etCode.setText(result);
            String code = etCode.getText().toString();
            etCode.setText("");
            if (CommonUtil.isEmpty(code)) {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), "请扫码后提交", Toast.LENGTH_SHORT).show();
                return;
            }
            code = CommonUtil.cleanCode(code);
            if(code.length() != 10 ){
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), "数据格式不正确", Toast.LENGTH_SHORT).show();
                tvResult.setText("数据格式不正确");
                etCode.setText("");
                etCode.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etCode.requestFocus();
                    }
                },500);
                return;
            }
            String begin = "08 11 00 16 00 00 00 ";
            String middle = convert(code);
            String end = "30 30 30 30 30 30 30 30 30 30 0D 0A 09";
            String convert = begin+middle+end;
            byte[] newData = hexStr2bytes(convert);
            sendNumberThread = new SendNumberThread(manager.getSocket(),myhandler,newData,code);
            sendNumberThread.start();
            etCode.postDelayed(new Runnable() {
                @Override
                public void run() {
                    etCode.requestFocus();
                }
            },500);
            return;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect=findViewById(R.id.connect);
        photo = findViewById(R.id.photo);
        text=findViewById(R.id.text);

        tvResult = findViewById(R.id.tvResult);
        tvResult.setText("正在连接中");

        socketinit(CONNECT,8899);
        etCode = findViewById(R.id.etCode);

        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                socketinit(CONNECT,8899);
            }
        });

        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission();

                //启动扫码
//                Intent intent = new Intent(MainActivity.this);
//                startActivityForResult(intent,REQUEST_CODE_SCAN);
                IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
                        //设置要扫码的类型
                        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                        intentIntegrator.setCaptureActivity(ScanAcitvity.class);
                        intentIntegrator.setPrompt("请扫描二维码");
                        //设置前置摄像头或者后置摄像头
                        intentIntegrator.setCameraId(0);
                        //扫描成功的哔哔声，默认开启
//                        intentIntegrator.setBeepEnabled(false);
                        //是否保留扫码成功后的截图
                        intentIntegrator.setBarcodeImageEnabled(true);
                        intentIntegrator.initiateScan();
            }
        });



        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    String code = etCode.getText().toString();
                    etCode.setText("");
                    if (CommonUtil.isEmpty(code)) {
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), "请扫码后提交", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    code = CommonUtil.cleanCode(code);
                    if(code.length() != 10 ){
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), "数据格式不正确", Toast.LENGTH_SHORT).show();
                        tvResult.setText("数据格式不正确");
                        etCode.setText("");
                        etCode.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                etCode.requestFocus();
                            }
                        },500);
                        return true;
                    }
                    String begin = "08 11 00 16 00 00 00 ";
                    String middle = convert(code);
                    String end = "30 30 30 30 30 30 30 30 30 30 0D 0A 09";
                    String convert = begin+middle+end;
                    byte[] data = hexStr2bytes(convert);
                    sendNumberThread = new SendNumberThread(manager.getSocket(),myhandler,data,code);
                    sendNumberThread.start();
                    etCode.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            etCode.requestFocus();
                        }
                    },500);

                    return true;
                }
                return false;
            }
        });
    }

    /**
     * socket连接方法
     * @param IP
     * @param post
     */
    public void socketinit(String IP, int post) {
        connectorThread = new SocketConnectorThread(IP, post, myhandler);
        connectorThread.start();  //开启链接服务器的线程
        Toast.makeText(MainActivity.this, IP + " " + post, Toast.LENGTH_SHORT).show();
    }



    public static byte[] hexStr2bytes(String hexStr) {
        hexStr = hexStr.replace(" ", "");
        if(hexStr.length()%2 != 0) {//长度为单数
            hexStr = " " + hexStr;//前面补空格
        }
        char[] chars = hexStr.toCharArray();
        int len = chars.length/2;
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++) {
            int x = i*2;
            bytes[i] = (byte)Integer.parseInt(String.valueOf(new char[]{chars[x], chars[x+1]}), 16);
        }
        return bytes;
    }

    public static String convert(String code){
        List<String> Array = new ArrayList<>();
        String str = "";
        for(int i = 0 ; i < code.length() ; i ++){
            Array.add("3"+code.substring(i,i+1)+" ");
        }
        for(int i = 0; i <Array.size() ; i ++){
            str += Array.get(i);
        }

        return str;
    }

    public void getPermission(){
        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission(
                "android.permission.CAMERA","com.example.socketdemo"));
        if(permission){
            //有无权限
            Toast.makeText(MainActivity.this,"有权限",Toast.LENGTH_SHORT).show();
        }else{
            //没有权限
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                requestPermissions(new String[]{Manifest.permission.CAMERA},15);
            }
        }
    }

}
